<template>
  <div class="role-management-page">
    <el-tree
        v-if="loaded"
        ref="permRef"
        :data="perm"
        show-checkbox
        node-key="rid"
        :default-expanded-keys="expandedKeys"
        :default-checked-keys="permsIds"
        :props="defaultProps"
    />
    <el-row class="button-row">
      <el-button type="primary" @click="handleAdd" plain>新增</el-button>
      <el-button type="danger" @click="handleDelete" plain>删除</el-button>
    </el-row>
    <!-- 新增权限对话框 -->
    <el-dialog
        v-model="dialogVisible"
        title="新增权限"
        width="30%"
        :before-close="handleClose"
    >
      <el-form :model="rolePermVo">
        <el-form-item label="角色名称" :label-width="formLabelWidth">
          <el-select v-model="rolePermVo.roleId" @change="onRoleChange" placeholder="请选择角色">
            <el-option
                v-for="role in roles"
                :key="role.id"
                :label="role.roleName"
                :value="role.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限名称" :label-width="formLabelWidth">
          <el-select v-model="rolePermVo.permId"  placeholder="请选择权限">
            <el-option
                v-for="perm in addPerms"
                :key="perm.id"
                :label="perm.description"
                :value="perm.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="addPermissions"
        >确认</el-button
        >
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import axios from '../../http/axios'; // 确保引入配置好的 axios 实例
import {handleError, onMounted, ref} from 'vue';
import {ElMessage, ElMessageBox, ElTree} from 'element-plus'
import type Node from 'element-plus/es/components/tree/src/model/node'

const dialogVisible = ref(false);
const permRef = ref<InstanceType<typeof ElTree>>()
const loaded = ref(false);
const perm = ref([]);
const permList = ref([]);
const permsIds = ref([]);
const expandedKeys = ref<number[]>([]);
const permissionObject = {
  permsIds: []
};
const formLabelWidth = '150px';
const rolePermVo = ref({
  roleId: '',
  permId: ''
});
const addPerms = ref([])
const roles = ref([]);
const defaultProps = {
  children: 'permList',
  label: 'description',
};

// 查询某个角色下拥有的权限
const getPerms = async function () {
  try {
    const response = await axios.get('/sys/perm/list');
    const {data} = response.data; // 假设后端返回的数据格式
    perm.value = formatData(data); //
    expandedKeys.value = perm.value.map(item => item.rid);
    loaded.value = true; // 加载完成后设置为 true
  } catch (error) {
    console.error(error);
  }
};
//根据选择的角色，获取未分配的权限
// 角色选择变化
// 角色选择变化
const onRoleChange = (roleId) => {
  //发送请求
  axios.get('/sys/perm/listNoPerm/'+roleId)
      .then((response) => {
        if (response.data.code === 200) {
          addPerms.value = response.data.data;
        } else {
          ElMessage.error(response.data.message);
        }
      });
};


// 查询所有权限列表
const getAllPerms = async function () {
  try {
    const response = await axios.get('/sys/perm/listAll');
    permList.value = response.data; // 假设后端返回的数据格式
    loaded.value = true; // 加载完成后设置为 true
  } catch (error) {
    console.error(error);
  }
}

// 获取选中的节点
function getSelectedNodes() {
  return permRef.value?.getCheckedNodes(true, true);
}
const cancel = () => {
  dialogVisible.value = false;
  resetDialog();
}
//新增
const handleAdd = () => {
  dialogVisible.value = true;
  getRoles(); // 获取所有角色
};
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确认关闭对话框?')
      .then(() => {
        resetDialog();
        done()
      })
      .catch(() => {
        // catch error
      })
}
// 获取所有角色
const getRoles = () => {
  axios.get('/sys/role/list')
      .then((response) => {
        if (response.data.code === 200) {
          roles.value = response.data.data;
        } else {
          ElMessage.error(response.data.message);
        }
      })
      .catch((e) => {
        console.log(e);
      })
};
// 添加权限
const addPermissions =() => {
  //如果角色id和权限id为空，则提示错误
  if (!rolePermVo.value.roleId || !rolePermVo.value.permId) {
    ElMessage.warning('请选择角色和权限');
    return;
  }
  //发送post请求
  axios.post('/sys/perm/add', rolePermVo.value)
      .then((response) => {
        if (response.data.code === 200) {
          ElMessage.success('添加成功');
          dialogVisible.value = false;
          resetDialog();
          getPerms(); // 重新加载权限数据
        } else {
          ElMessage.error(response.data.message);
        }
      })
};

// 重置对话框
const resetDialog = () => {
  rolePermVo.value = {
    roleId: '',
    permId: ''};
  addPerms.value = [];
  roles.value = [];
};
//删除
const handleDelete = () => {
  const selectedNodes = getSelectedNodes();
  // 判断是否选择了要删除的权限
  if (!selectedNodes || selectedNodes.length === 0) {
    ElMessage.warning('请选择要删除的权限');
    return;
  }
  //遍历node数组，将rid和pid数组封装进permissionObject,组成一个新数组
  permissionObject.permsIds = selectedNodes.map(node => {
    return {
      rid: node.rid,
      pid: node.pid
    };
  });
  console.log(permissionObject.permsIds)
  // 发送请求给后端来删除这些权限
  axios.post('/sys/perm/delete', permissionObject.permsIds)
      .then(response => {
        if (response.data.code === 200) {
          // 删除成功
          ElMessage.success('删除成功');
        } else {
          ElMessage.error(response.data.message)
        }
        // 重新加载数据
        getPerms();
      })
      .catch(error => {
        // 删除失败
        ElMessage.error('删除失败');
      });
  // 实际应用中，您需要在这里调用后端API进行删除操作
};

// 格式化数据
function formatData(data) {
  // 根据实际情况格式化数据
  //过滤掉数据permList中pid为空的数据，
  // 假设数据已经按照正确的格式返回
  return data;
}


onMounted(() => {
  getPerms(); // 页面加载完成时获取数据
  getAllPerms();
  getRoles();
});
</script>

<style lang="scss" scoped>

.role-management-page {
  width: 100%;
  box-sizing: border-box;
  padding: 20px;
  background-color: #fff;
  overflow: auto;
  position: relative;

  .el-tree {
    margin-bottom: 20px;
    background-color: #fff;
    border-radius: 4px;
    padding: 10px;
  }

  .leave-management-page {
    padding: 20px;
  }

  .dialog-footer {
    text-align: right;
  }

  /* Ensure styles apply to el-dialog */
  :deep(.el-dialog) {
    position: fixed !important;
    top: 50% !important;
    left: 50% !important;
    transform: translate(-50%, -50%) !important;
    max-width: 90% !important;
    max-height: 80vh !important;
  }

  /* Center the dialog body content */
  :deep(.el-dialog__body) {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  /* Ensure the dialog header is centered */
  :deep(.el-dialog__header) {
    text-align: center;
  }

  :deep(.el-dialog__body .el-form) {
    width: 100%;
  }

  :deep(.el-dialog__body .el-form-item) {
    margin-bottom: 20px; /* Adjust space between form items */
  }

  .button-row {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    .el-button {
      padding: 10px 20px;
      font-size: 16px;
      border-radius: 4px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.15);
      }
    }
  }
}
</style>